 package server;



import client.inventory.Item;
import client.inventory.ItemLoader;
import client.inventory.MapleInventoryType;
import com.alibaba.druid.pool.DruidPooledConnection;
import constants.ItemConstants;
import database.DatabaseConnection;
import tools.Pair;
import tools.packet.MTSCSPacket;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;






















 public class MTSStorage
 {
   private static MTSStorage instance;
   private final Map<Integer, MTSCart> idToCart;
   private final AtomicInteger packageId;
/*  29 */   private long lastUpdate = System.currentTimeMillis(); private final Map<Integer, MTSItemInfo> buyNow;
   private final ReentrantReadWriteLock mutex;
   private final ReentrantReadWriteLock cart_mutex;
   private boolean end = false;

   public MTSStorage() {
/*  35 */     this.idToCart = new LinkedHashMap<>();
/*  36 */     this.buyNow = new LinkedHashMap<>();
/*  37 */     this.packageId = new AtomicInteger(1);
/*  38 */     this.mutex = new ReentrantReadWriteLock();
/*  39 */     this.cart_mutex = new ReentrantReadWriteLock();
   }

   public static MTSStorage getInstance() {
/*  43 */     return instance;
   }

   public static void load() {
/*  47 */     if (instance == null) {
/*  48 */       instance = new MTSStorage();
/*  49 */       instance.loadBuyNow();
     }
   }

   public boolean check(int packageid) {
/*  54 */     return (getSingleItem(packageid) != null);
   }

   public boolean checkCart(int packageid, int charID) {
/*  58 */     MTSItemInfo item = getSingleItem(packageid);
/*  59 */     return (item != null && item.getCharacterId() != charID);
   }

   public MTSItemInfo getSingleItem(int packageid) {
/*  63 */     this.mutex.readLock().lock();
     try {
/*  65 */       return this.buyNow.get(Integer.valueOf(packageid));
     } finally {
/*  67 */       this.mutex.readLock().unlock();
     }
   }

   public void addToBuyNow(MTSCart cart, Item item, int price, int cid, String seller, long expiration) {
     int id;
/*  73 */     this.mutex.writeLock().lock();
     try {
/*  75 */       id = this.packageId.incrementAndGet();
/*  76 */       this.buyNow.put(Integer.valueOf(id), new MTSItemInfo(price, item, seller, id, cid, expiration));
     } finally {
/*  78 */       this.mutex.writeLock().unlock();
     }
/*  80 */     cart.addToNotYetSold(id);
   }

   public boolean removeFromBuyNow(int id, int cidBought, boolean check) {
/*  84 */     Item item = null;
/*  85 */     this.mutex.writeLock().lock();
     try {
/*  87 */       if (this.buyNow.containsKey(Integer.valueOf(id))) {
/*  88 */         MTSItemInfo r = this.buyNow.get(Integer.valueOf(id));
/*  89 */         if (!check || r.getCharacterId() == cidBought) {
/*  90 */           item = r.getItem();
/*  91 */           this.buyNow.remove(Integer.valueOf(id));
         }
       }
     } finally {
/*  95 */       this.mutex.writeLock().unlock();
     }
/*  97 */     if (item != null) {
/*  98 */       this.cart_mutex.readLock().lock();
       try {
/* 100 */         for (Map.Entry<Integer, MTSCart> c : this.idToCart.entrySet()) {
/* 101 */           ((MTSCart)c.getValue()).removeFromCart(id);
/* 102 */           ((MTSCart)c.getValue()).removeFromNotYetSold(id);
/* 103 */           if (((Integer)c.getKey()).intValue() == cidBought) {
/* 104 */             ((MTSCart)c.getValue()).addToInventory(item);
           }
         }
       } finally {
/* 108 */         this.cart_mutex.readLock().unlock();
       }
     }
/* 111 */     return (item != null);
   }

   private void loadBuyNow() {
/* 115 */     int lastPackage = 0;


/* 118 */     try (DruidPooledConnection con = DatabaseConnection.getInstance().getConnection()) {
/* 119 */       PreparedStatement ps = con.prepareStatement("SELECT * FROM mts_items WHERE tab = 1");
/* 120 */       ResultSet rs = ps.executeQuery();
/* 121 */       while (rs.next()) {
/* 122 */         lastPackage = rs.getInt("id");
/* 123 */         int charId = rs.getInt("characterid");
/* 124 */         if (!this.idToCart.containsKey(Integer.valueOf(charId))) {
/* 125 */           this.idToCart.put(Integer.valueOf(charId), new MTSCart(charId));
         }
/* 127 */         Map<Long, Pair<Item, MapleInventoryType>> items = ItemLoader.拍卖道具.loadItems(false, lastPackage);
/* 128 */         if (items != null && items.size() > 0) {
/* 129 */           for (Pair<Item, MapleInventoryType> i : items.values()) {
/* 130 */             this.buyNow.put(Integer.valueOf(lastPackage), new MTSItemInfo(rs.getInt("price"), (Item)i.getLeft(), rs.getString("seller"), lastPackage, charId, rs.getLong("expiration")));
           }
         }
       }
/* 134 */       rs.close();
/* 135 */       ps.close();
/* 136 */     } catch (Exception e) {
/* 137 */       e.printStackTrace();
     }
/* 139 */     this.packageId.set(lastPackage);
   }

   public void saveBuyNow(boolean isShutDown) {
/* 143 */     if (this.end) {
       return;
     }
/* 146 */     this.end = isShutDown;
/* 147 */     if (isShutDown) {
/* 148 */       System.out.println("正在保存 MTS...");
     }
/* 150 */     Map<Integer, ArrayList<Item>> expire = new HashMap<>();
/* 151 */     List<Integer> toRemove = new ArrayList<>();
/* 152 */     long now = System.currentTimeMillis();
/* 153 */     Map<Integer, ArrayList<Pair<Item, MapleInventoryType>>> items = new HashMap<>();
/* 154 */     this.mutex.writeLock().lock();
/* 155 */     try (DruidPooledConnection con = DatabaseConnection.getInstance().getConnection()) {
/* 156 */       PreparedStatement ps = con.prepareStatement("DELETE FROM mts_items WHERE tab = 1");
/* 157 */       ps.execute();
/* 158 */       ps.close();
/* 159 */       ps = con.prepareStatement("INSERT INTO mts_items VALUES (?, ?, ?, ?, ?, ?)");
/* 160 */       for (MTSItemInfo m : this.buyNow.values()) {
/* 161 */         if (now > m.getEndingDate()) {
/* 162 */           if (!expire.containsKey(Integer.valueOf(m.getCharacterId()))) {
/* 163 */             expire.put(Integer.valueOf(m.getCharacterId()), new ArrayList<>());
           }
/* 165 */           ((ArrayList<Item>)expire.get(Integer.valueOf(m.getCharacterId()))).add(m.getItem());
/* 166 */           toRemove.add(Integer.valueOf(m.getId()));
/* 167 */           items.put(Integer.valueOf(m.getId()), null); continue;
         }
/* 169 */         ps.setInt(1, m.getId());
/* 170 */         ps.setByte(2, (byte)1);
/* 171 */         ps.setInt(3, m.getPrice());
/* 172 */         ps.setInt(4, m.getCharacterId());
/* 173 */         ps.setString(5, m.getSeller());
/* 174 */         ps.setLong(6, m.getEndingDate());
/* 175 */         ps.executeUpdate();
/* 176 */         if (!items.containsKey(Integer.valueOf(m.getId()))) {
/* 177 */           items.put(Integer.valueOf(m.getId()), new ArrayList<>());
         }
/* 179 */         items.get(m.getId()).add(new Pair<>(m.getItem(), ItemConstants.getInventoryType(m.getItem().getItemId())));
       }

/* 182 */       for (Iterator<Integer> iterator = toRemove.iterator(); iterator.hasNext(); ) { int i = ((Integer)iterator.next()).intValue();
/* 183 */         this.buyNow.remove(Integer.valueOf(i)); }

/* 185 */       ps.close();
/* 186 */     } catch (SQLException e) {
/* 187 */       e.printStackTrace();
     } finally {
/* 189 */       this.mutex.writeLock().unlock();
     }
/* 191 */     if (isShutDown) {
/* 192 */       System.out.println("正在保存 MTS 道具信息...");
     }
     try {
/* 195 */       for (Map.Entry<Integer, ArrayList<Pair<Item, MapleInventoryType>>> ite : items.entrySet()) {
/* 196 */         ItemLoader.拍卖道具.saveItems(null, ite.getValue(), ((Integer)ite.getKey()).intValue());
       }
/* 198 */     } catch (SQLException e) {
/* 199 */       e.printStackTrace();
     }
/* 201 */     if (isShutDown) {
/* 202 */       System.out.println("正在保存 MTS carts...");
     }
/* 204 */     this.cart_mutex.writeLock().lock();
     try {
/* 206 */       for (Map.Entry<Integer, MTSCart> c : this.idToCart.entrySet()) {
/* 207 */         Iterator<Integer> iterator; for (iterator = toRemove.iterator(); iterator.hasNext(); ) { int i = ((Integer)iterator.next()).intValue();
/* 208 */           ((MTSCart)c.getValue()).removeFromCart(i);
/* 209 */           ((MTSCart)c.getValue()).removeFromNotYetSold(i); }

/* 211 */         if (expire.containsKey(c.getKey())) {
/* 212 */           for (Item item : expire.get(c.getKey())) {
/* 213 */             ((MTSCart)c.getValue()).addToInventory(item);
           }
         }
/* 216 */         ((MTSCart)c.getValue()).save();
       }
/* 218 */     } catch (SQLException e) {
/* 219 */       e.printStackTrace();
     } finally {
/* 221 */       this.cart_mutex.writeLock().unlock();
     }
/* 223 */     this.lastUpdate = System.currentTimeMillis();
   }

   public void checkExpirations() {
/* 227 */     if (System.currentTimeMillis() - this.lastUpdate > 3600000L) {
/* 228 */       saveBuyNow(false);
     }
   }

   public MTSCart getCart(int characterId) {
     MTSCart ret;
/* 234 */     this.cart_mutex.readLock().lock();
     try {
/* 236 */       ret = this.idToCart.get(Integer.valueOf(characterId));
     } finally {
/* 238 */       this.cart_mutex.readLock().unlock();
     }
/* 240 */     if (ret == null) {
/* 241 */       this.cart_mutex.writeLock().lock();
       try {
/* 243 */         ret = new MTSCart(characterId);
/* 244 */         this.idToCart.put(Integer.valueOf(characterId), ret);
/* 245 */       } catch (SQLException e) {
/* 246 */         e.printStackTrace();
       } finally {
/* 248 */         this.cart_mutex.writeLock().unlock();
       }
     }
/* 251 */     return ret;
   }

   public byte[] getCurrentMTS(MTSCart cart) {
/* 255 */     this.mutex.readLock().lock();
     try {
/* 257 */       return MTSCSPacket.INSTANCE.sendMTS(getMultiItems(cart.getCurrentView(), cart.getPage()), cart.getTab(), cart.getType(), cart.getPage(), cart.getCurrentView().size());
     } finally {
/* 259 */       this.mutex.readLock().unlock();
     }
   }

   public byte[] getCurrentNotYetSold(MTSCart cart) {
/* 264 */     this.mutex.readLock().lock();
     try {
/* 266 */       List<MTSItemInfo> nys = new ArrayList<>();

/* 268 */       List<Integer> nyss = new ArrayList<>(cart.getNotYetSold());
/* 269 */       for (Iterator<Integer> iterator = nyss.iterator(); iterator.hasNext(); ) { int i = ((Integer)iterator.next()).intValue();
/* 270 */         MTSItemInfo r = this.buyNow.get(Integer.valueOf(i));
/* 271 */         if (r == null) {
/* 272 */           cart.removeFromNotYetSold(i); continue;
         }
/* 274 */         nys.add(r); }


/* 277 */       return MTSCSPacket.INSTANCE.getNotYetSoldInv(nys);
     } finally {
/* 279 */       this.mutex.readLock().unlock();
     }
   }

   public byte[] getCurrentTransfer(MTSCart cart, boolean changed) {
/* 284 */     return MTSCSPacket.INSTANCE.getTransferInventory(cart.getInventory(), changed);
   }

   public List<MTSItemInfo> getMultiItems(List<Integer> items, int pageNumber) {
/* 288 */     List<MTSItemInfo> ret = new ArrayList<>();

/* 290 */     List<Integer> cartt = new ArrayList<>(items);
/* 291 */     if (pageNumber > cartt.size() / 16 + ((cartt.size() % 16 > 0) ? 1 : 0)) {
/* 292 */       pageNumber = 0;
     }
/* 294 */     int maxSize = Math.min(cartt.size(), pageNumber * 16 + 16);
/* 295 */     int minSize = Math.min(cartt.size(), pageNumber * 16);
/* 296 */     for (int i = minSize; i < maxSize && 
/* 297 */       cartt.size() > i; i++) {
/* 298 */       MTSItemInfo r = this.buyNow.get(cartt.get(i));
/* 299 */       if (r == null) {
/* 300 */         items.remove(i);
/* 301 */         cartt.remove(i);
       } else {
/* 303 */         ret.add(r);
       }
     }



/* 309 */     return ret;
   }

   public List<Integer> getBuyNow(int type) {
/* 313 */     this.mutex.readLock().lock();
     try {
/* 315 */       if (type == 0) {
/* 316 */         return new ArrayList(this.buyNow.keySet());
       }


/* 320 */       List<MTSItemInfo> ret = new ArrayList<>(this.buyNow.values());
/* 321 */       List<Integer> rett = new ArrayList<>();

/* 323 */       for (MTSItemInfo aRet : ret) {
/* 324 */         MTSItemInfo r = aRet;
/* 325 */         if (r != null && ItemConstants.getInventoryType(r.getItem().getItemId()).getType() == type) {
/* 326 */           rett.add(Integer.valueOf(r.getId()));
         }
       }
/* 329 */       return rett;
     } finally {
/* 331 */       this.mutex.readLock().unlock();
     }
   }

   public List<Integer> getSearch(boolean item, String name, int type, int tab) {
/* 336 */     this.mutex.readLock().lock();
     try {
/* 338 */       MapleItemInformationProvider ii = MapleItemInformationProvider.getInstance();
/* 339 */       if (tab != 1 || name.length() <= 0) {
/* 340 */         return new ArrayList();
       }
/* 342 */       name = name.toLowerCase();
/* 343 */       List<MTSItemInfo> ret = new ArrayList<>(this.buyNow.values());
/* 344 */       List<Integer> rett = new ArrayList<>();

/* 346 */       for (MTSItemInfo aRet : ret) {
/* 347 */         MTSItemInfo r = aRet;
/* 348 */         if (r != null && (type == 0 || ItemConstants.getInventoryType(r.getItem().getItemId()).getType() == type)) {
/* 349 */           String thename = item ? ii.getName(r.getItem().getItemId()) : r.getSeller();
/* 350 */           if (thename != null && thename.toLowerCase().contains(name)) {
/* 351 */             rett.add(Integer.valueOf(r.getId()));
           }
         }
       }
/* 355 */       return rett;
     } finally {
/* 357 */       this.mutex.readLock().unlock();
     }
   }

   public List<MTSItemInfo> getCartItems(MTSCart cart) {
/* 362 */     return getMultiItems(cart.getCart(), cart.getPage());
   }

   public static class MTSItemInfo
   {
     private final int price;
     private final Item item;
     private final String seller;
     private final int id;
     private final int cid;
     private final long date;

     public MTSItemInfo(int price, Item item, String seller, int id, int cid, long date) {
/* 375 */       this.item = item;
/* 376 */       this.price = price;
/* 377 */       this.seller = seller;
/* 378 */       this.id = id;
/* 379 */       this.cid = cid;
/* 380 */       this.date = date;
     }

     public Item getItem() {
/* 384 */       return this.item;
     }

     public int getPrice() {
/* 388 */       return this.price;
     }

     public int getRealPrice() {
/* 392 */       return this.price + getTaxes();
     }

     public int getTaxes() {
/* 396 */       return 0 + this.price * 5 / 100;
     }

     public int getId() {
/* 400 */       return this.id;
     }

     public int getCharacterId() {
/* 404 */       return this.cid;
     }

     public long getEndingDate() {
/* 408 */       return this.date;
     }

     public String getSeller() {
/* 412 */       return this.seller;
     }
   }
 }


/* Location:              C:\PGX\Server.jar!\server\MTSStorage.class
 * Java compiler version: 8 (52.0)
 * JD-Core Version:       1.1.3
 */